// 定义一个Fetch拦截器
export const interceptor = (request) => {
  // 在请求头中添加一个自定义的Authorization字段
  request.headers.set('X-Access-Token', 'xxx');
  // 返回修改后的请求对象
  return request;
};

export const post = (url, params) => {
  return fetch(url, {
    method: 'post',
    body: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/json',
    },
    interceptor
  }).then((res) => res.json())
}

export const postFD = (url, params) => {
  const fd = new FormData()
  for (let item in params) {
    if (Array.isArray(params[item])) {
      for (let i in params[item]) {
        fd.append(item, params[item][i])
      }
    } else {
      fd.append(item, params[item])
    }
  }
  return fetch(url, {
    method: 'post',
    body: fd,
    interceptor
  }).then((res) => res.json())
}

export const exportFile = (url, params) => {
  return fetch(url, {
    method: 'post',
    body: JSON.stringify(params),
    headers: {
      'Content-Type': 'application/json',
    },
    interceptor
  }).then((res) => res.blob())
}